package com.school.sports.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 密码重置工具类
 * 用于重置数据库中用户的密码为正确的BCrypt哈希值
 *
 * @author 系统开发团队
 * @since 2025-10-14
 */
@Slf4j
@Component
@Order(2)
public class PasswordResetUtil implements CommandLineRunner {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始检查用户密码哈希值...");

        // 检查并重置默认用户的密码
        resetDefaultPasswords();

        log.info("用户密码哈希值检查完成");
    }

    /**
     * 重置默认用户的密码
     */
    private void resetDefaultPasswords() {
        // 默认用户密码映射
        String[][] defaultUsers = {
            {"admin", "123456"},
            {"teacher1", "123456"},
            {"student1", "123456"},
            {"student2", "123456"},
            {"referee1", "123456"},
            {"volunteer1", "123456"}
        };

        try (Connection connection = dataSource.getConnection()) {
            for (String[] user : defaultUsers) {
                String username = user[0];
                String plainPassword = user[1];

                // 查询用户当前的密码哈希
                String selectSql = "SELECT id, password_hash FROM user WHERE username = ?";
                try (PreparedStatement selectStmt = connection.prepareStatement(selectSql)) {
                    selectStmt.setString(1, username);
                    try (ResultSet rs = selectStmt.executeQuery()) {
                        if (rs.next()) {
                            Long userId = rs.getLong("id");
                            String currentHash = rs.getString("password_hash");

                            // 生成新的密码哈希
                            String newHash = passwordEncoder.encode(plainPassword);

                            // 检查当前密码哈希是否正确
                            if (passwordEncoder.matches(plainPassword, currentHash)) {
                                log.info("用户 {} 的密码哈希值正确，无需更新", username);
                            } else {
                                // 更新密码哈希
                                String updateSql = "UPDATE user SET password_hash = ? WHERE id = ?";
                                try (PreparedStatement updateStmt = connection.prepareStatement(updateSql)) {
                                    updateStmt.setString(1, newHash);
                                    updateStmt.setLong(2, userId);
                                    int affectedRows = updateStmt.executeUpdate();

                                    if (affectedRows > 0) {
                                        log.info("已更新用户 {} 的密码哈希值", username);
                                    } else {
                                        log.warn("更新用户 {} 的密码哈希值失败", username);
                                    }
                                }
                            }
                        } else {
                            log.warn("用户 {} 不存在", username);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("重置用户密码失败：{}", e.getMessage(), e);
        }
    }
}